package org.one.afternoon.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.one.afternoon.common.Result;
import org.one.afternoon.domain.Record;
import org.one.afternoon.provider.xunfei.ChatListener;
import org.one.afternoon.service.RecordService;
import org.one.afternoon.utils.Splitter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping(value = "/chat")
@Slf4j
public class ChatController {

    @Autowired
    RecordService recordService;

    private final Gson gson = new Gson();

    private int maxTextLength = 75;

    @CrossOrigin
    @PostMapping("/kdxf/form")
    @ResponseBody
    public Result<String> connectWithFormData(@RequestParam String question) {

        LambdaQueryWrapper<Record> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotBlank(question), Record::getQuestion, question);
        if (recordService.list(lambdaQueryWrapper) == null || recordService.list(lambdaQueryWrapper).isEmpty()) {
            try {
                ChatListener.connect(question);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
            while (true) {
                if (ChatListener.end) break;
            }

            Record record = new Record();
            record.setQuestion(question);
            record.setAnswer(ChatListener.totalAnswer);
            recordService.save(record);

            return Result.success(ChatListener.totalAnswer);
        }
        return Result.success(recordService.list(lambdaQueryWrapper).get(0).getAnswer());
    }

    @CrossOrigin
    @PostMapping("/kdxf/json")
    @ResponseBody
    public Result<String[]> connectWithJsonData(@RequestBody Record mes) {

        log.info(mes.toString());

        String issue = gson.fromJson(mes.getQuestion(), String.class);
        LambdaQueryWrapper<Record> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotBlank(issue), Record::getQuestion, issue);
        log.info("①:缓存机制开启...");
        if (recordService.list(lambdaQueryWrapper) == null || recordService.list(lambdaQueryWrapper).isEmpty()) {
            log.info("②:未在数据库找到类似问题...");
            try {
                log.info("③:即将开始连接WebSocket...");
                ChatListener.connect(issue);
            } catch (Exception e) {
                log.error(e.getMessage());
            }

//            ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
//            scheduler.scheduleAtFixedRate(() -> {
//                if (!Chat.end) {
//                    log.info("循环中...    end=" + Chat.end);
//                }
//            }, 0, 10, TimeUnit.SECONDS);

            log.info("④:正在从WebSocket获取数据...");

            while (true) {
                if (ChatListener.end) break;
            }

            log.info(ChatListener.totalAnswer);
//            try {
//                Thread.sleep(40000); // 等待10秒，10000毫秒
//            } catch (InterruptedException e) {
//                // 如果在等待期间线程被中断，会抛出 InterruptedException
//                // 在这里你可以处理中断情况，比如记录日志或重新设置中断状态
//                Thread.currentThread().interrupt(); // 通常，最好保留中断状态
//            }

//            Chat.wsCloseFlag=false;
            log.info("⑤:已断开WebSocket连接,即将把新问题即答案写入数据库...");
            Record record = new Record();
            record.setQuestion(issue);
            record.setAnswer(ChatListener.totalAnswer);
            recordService.save(record);

            log.info("⑥:成功将数据写入数据库...");

            String[] result = Splitter.Splitter(ChatListener.totalAnswer, maxTextLength);
            return Result.success(result);
        }

        log.info("⑦:成功在数据库找到类似问题,将直接返回数据...");
        return Result.success(Splitter.Splitter(recordService.list(lambdaQueryWrapper).get(0).getAnswer(), maxTextLength));
    }
}
